package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.tbvtc.agriculturalcreditchainserver2025.comment.iot.Enm.LED;
import com.tbvtc.agriculturalcreditchainserver2025.comment.iot.Enm.Sensor;
import com.tbvtc.agriculturalcreditchainserver2025.comment.iot.IoTAPI;
import com.tbvtc.agriculturalcreditchainserver2025.comment.iot.KguHttpClient;
import com.tbvtc.agriculturalcreditchainserver2025.entity.CameraCropMapping;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Crop;
import com.tbvtc.agriculturalcreditchainserver2025.entity.UserDevice;
import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CameraCropMappingMapper;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CropMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.IUserDeviceService;
import com.tbvtc.agriculturalcreditchainserver2025.service.IoTApiService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestConstant;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import com.tbvtc.agriculturalcreditchainserver2025.utils.ResultCodeEnum;
import com.tbvtc.agriculturalcreditchainserver2025.utils.huawei.HwCloudIot;
import io.swagger.v3.oas.annotations.Operation;

import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@Tag(name = "控制器")
@CrossOrigin
@RequestMapping("/iot")
public class IoTAPIController {
    @Autowired
    private IoTApiService ioTApiService;
    @Autowired
    private IUserDeviceService userDeviceService;
    @Resource
    private HwCloudIot hwCloudIot;
    @Autowired
    private CropMapper cropMapper;
    @Autowired
    private CameraCropMappingMapper camera;
    private static String token;
    KguHttpClient http = new KguHttpClient();

    @Operation(summary = "获取token")
    @PostMapping("/getToken")
    public Result getToken(@RequestBody UserDevice userDevice) throws Exception {
        String id = userDeviceService.insert(userDevice);
        HashMap<String, String> header = new HashMap();
        HashMap<String, String> body = new HashMap<>();

        header.put("Content-Type", "application/json");
        body.put("Account", userDevice.getUserName());
        body.put("Password", userDevice.getUserPassword());
        String returnMsg = "";
        try {
            returnMsg = http.post("http://api.nlecloud.com/users/login", body, header);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        Map map = new HashMap<>();
        map.put("token", returnMsg);
        map.put("id", id);
        return RUtils.success(map);
    }

    @Operation(summary = "火焰传感器")
    @PostMapping("/iotFire")
    public Result iot(HttpServletRequest request) throws InterruptedException, JsonProcessingException {
        String header = request.getHeader("token");
        ioTApiService.iotFire();
        IoTAPI iot = new IoTAPI();
        String s = iot.getSensorsData(Sensor.hycgq);
        return RUtils.success();
    }

    /**
     * @return
     * @throws InterruptedException
     */
    @Operation(summary = "风扇控制器")
    @PostMapping("/ioFen")
    public Result ioFen(@RequestParam("isOpen") Boolean isOpen, HttpServletRequest request) throws InterruptedException {
        String header = request.getHeader("token");
//        System.out.println(header);
        ioTApiService.ioFenControl(isOpen, header);
        return RUtils.success();
    }


    /**
     * 警示灯控制器
     *
     * @param type
     * @return
     * @throws InterruptedException
     */
    @Operation(summary = "警示灯控制器")
    @PostMapping("/ioLight")
    public Result ioLight(@RequestParam("type") LED type, @RequestParam("isOpen") Boolean isOpen, HttpServletRequest request) throws InterruptedException {
        String header = request.getHeader("token");
        ioTApiService.ioLightControl(type, isOpen, header);
        return RUtils.success();
    }

    @Operation(summary = "水泵灯控制器")
    @PostMapping("/ioWaterpump")
    @Transactional(rollbackFor = Exception.class)
    public Result ioWaterpump(@RequestParam("isOpen") String isOpen) throws InterruptedException {
        if ("on".equals(isOpen)) {
                CameraCropMapping cameraCropMapping = camera.selectById(PestConstant.cameraId); //通过摄像头id获取到绑定的农作物id
                Crop cropDto = cropMapper.selectById(cameraCropMapping.getCropId());
                cropMapper.cancelPest(cropDto.getName());
            }
        return RUtils.success();
    }

    @Operation(summary = "智能插座控制器")
    @PostMapping("/ioSocket")
    @Parameter(name = "isOpen", description = "插座开关(0表示关，1表示开)")
    public Result ioSocket(@RequestParam("isOpen") String isOpen) {

        return RUtils.success(  ioTApiService.smartSockets(isOpen));
    }

    /**
     * 获取温湿度
     * @return
     * @throws Exception
     */
    @Operation(summary = "获取温湿度")
    @GetMapping("/getTemHum")
    public Result getIlluminationValue() throws Exception {
        return RUtils.success(hwCloudIot.getTemAndHumInfo());

    }


}
